﻿using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System.Text;
using Xunit;
using Xunit.Abstractions;
namespace Odyssey.Consul.xUnit
{
    using Http;
    public class xUnitKVStore
    {
        ITestOutputHelper outputHelper;

        public xUnitKVStore(ITestOutputHelper output)
        {
            outputHelper = output;
        }

        private ConsulDispatch BuildConsul()
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddLogging();
            serviceCollection.AddOdysseyHttp((httpConfiguration) =>
            {
                httpConfiguration.JsonSerializerSettingsBuilder = () =>
                {
                    return new JsonSerializerSettings()
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                        DefaultValueHandling = DefaultValueHandling.Ignore,
                    };
                };
                httpConfiguration.HttpResponseFilter = async (httpResponseMessage) =>
                {
                    if (httpResponseMessage.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        var errorContent = await httpResponseMessage.Content.ReadAsStringAsync();
                        outputHelper.WriteLine(errorContent);
                        httpResponseMessage.EnsureSuccessStatusCode();
                    }
                };
            }).AddConsulCore((consulConfiguration) =>
            {
                consulConfiguration.EnableAcl = true;
                consulConfiguration.Host = "http://localhost:8500";
                consulConfiguration.AccessorID = "9d4786d8-a073-0778-b45d-d4fc3197b19c";
                consulConfiguration.SecretID = "d163859b-8363-4e37-7acf-913be2fd66b5";

                //consulConfiguration.AccessorID = "9d4786d8-a073-0778-b45d-d4fc3197b19c";
                //consulConfiguration.SecretID = "2e08b156-f3f3-c072-adab-896833d44625";
            });

            return serviceCollection.BuildServiceProvider().GetRequiredService<ConsulDispatch>();
        }

        [Fact]
        public void CreateUpdateTest()
        {
            var consul = BuildConsul();
            if (consul.KVStore.CreateAndUpdate(new Models.ArguKVStore()
            {
                Key = "my-key",
                Value = Encoding.UTF8.GetBytes("my-value")
            }).Result)
            {
                var result = consul.KVStore.Read(new Models.ArguKVStore()
                {
                    Key = "my-key",
                }).Result;

                Assert.Equal("my-value", Encoding.UTF8.GetString(result[0].Value));
            }
            else
            {
                throw new System.Exception("faild");
            }

        }
    }
}
